package com.android.nearshop.app.activity.main;

import java.text.DecimalFormat;
import java.util.ArrayList;

import org.taptwo.android.widget.CircleFlowIndicator;
import org.taptwo.android.widget.ViewFlow;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Vibrator;
import android.text.Html;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.android.nearshop.R;
import com.android.nearshop.app.MyApplication;
import com.android.nearshop.app.activity.common.TemplateActivity;
import com.android.nearshop.app.activity.map.SelLocActivity;
import com.android.nearshop.app.activity.search.SearchActivity;
import com.android.nearshop.app.adapter.device.ShakeListener;
import com.android.nearshop.app.adapter.device.ShakeListener.OnShakeListener;
import com.android.nearshop.app.adapter.listadapter.AdvListAdapter;
import com.android.nearshop.app.widget.TitleBar;
import com.android.nearshop.app.widget.TitleBar.OnTitleClickListener;
import com.android.nearshop.business.cache.DataCacheManager;
import com.android.nearshop.business.location.MyBMapManager;
import com.android.nearshop.business.location.MyBMapManager.OnLocationListener;
import com.android.nearshop.business.model.Addr;
import com.android.nearshop.business.model.FindCondition;
import com.android.nearshop.io.protocol.ProtocolManager;
import com.android.nearshop.io.protocol.in.BannerAction.ADV_TYPE;
import com.android.nearshop.io.protocol.in.CountAction;
import com.android.nearshop.io.protocol.out.Area;
import com.android.nearshop.io.protocol.out.ShakeCount;
import com.android.nearshop.util.Constant;
import com.android.nearshop.util.CycledThread;
import com.android.nearshop.util.DataCache;
import com.android.nearshop.util.Log;
import com.android.nearshop.util.Util;
import com.baidu.mapapi.MKAddrInfo;

/*********************************************************
 * @author : zhaohua
 * @version : 2012-8-16
 * @see : 摇一摇主界面 
 * @Copyright : copyrights reserved by personal 2007-2011
 **********************************************************/
public class ShakeShopActivity extends TemplateActivity 
implements OnClickListener,OnShakeListener,OnLocationListener
{
    private static final String TX_SHAKE_NUM = "<b>“ </b> </strong> <font size='20' color='red'> %1$s </font></strong><b> ”</b>  次摇过";
    public static boolean isPopBack = false;
    // UI 成员
    private ViewFlow viewFlow;
    private ImageView shake_img;
    private TextView shake_num;
    private TextView   cate_0;
    private TextView   cate_1;
    private TextView   cate_2;
    private ImageView add_cate_img;
    private Button add_cate_bnt;
    private TextView address;
    private ImageView address_refresh;
    private ProgressBar loc_loading;
    private PopupWindow selLocPopWin;
    private ShakeListener shakeListener;
    private MyBMapManager mMapManager;  
    private AdvListAdapter mAdvAdapter;
    // 位置的选择
    private CycledThread mSlidAdvThread;
    private Location mCurLocation;
    // 选中的位置
    private Addr mAddr;
    // 选中的城市
    private Area mArea;
    // 商品分类的选择
    private ArrayList<Integer> mCateList;
    private Animation mShakeAnim;
    
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shakeshop);        
        initViews();        
        shakeListener = new ShakeListener(this);
        shakeListener.setOnShakeListener(this);
        mMapManager = MyBMapManager.getInstace(this);
    }
    
    @Override
    protected void onResume()
    {
        super.onResume();
        shakeListener.start();
        mAdvAdapter.loadMainAdvs();
        showShakeNumView();
        showCateViews();
        mMapManager.setOnLocationListener(this);
        mTitleBar.setLeftText(Util.getCityText(this));
        checkLocation();
        startAutoSlidAdv();
    }
    
    @Override
    protected void onPause()
    {
        shakeListener.stop();
        dissPop();
        stopAutoSlidAdv();
        super.onPause();
    }
    
    @Override
    public void onBackPressed() 
    {
        if(selLocPopWin == null && selLocPopWin.isShowing())
        {
            dissPop();
            return;
        }
        
        if( getParent() instanceof MainIndexActivity)
        {
            ((MainIndexActivity)getParent()).onBackPressed();
        }
    }
       
    @Override
    protected void setupTitleBar(TitleBar titleBar)
    {
        titleBar.setTitle(R.string.title_shake);
        titleBar.setRigthImage(R.drawable.search_normal);
        titleBar.setLeftBg(R.drawable.red_button_bg);
//        titleBar.getLeftTextView().setCompoundDrawablesWithIntrinsicBounds(0,0,R.drawable.icon_d3j,0);
        titleBar.setLeftText(Util.getCityText(this));
        
        titleBar.setOnTitleClickListener(new OnTitleClickListener()
        {
            @Override
            public void onLeftClick()
            {
                // 选择镇区
                showSelLocPopWin();
            }
            @Override
            public void onRightClick()
            {              
                // 开始查询，相当于摇一摇功能 test
            	Intent intent = new Intent();
            	intent.setClass(getApplicationContext(), SearchActivity.class);
            	intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
            	startActivity(intent);
            }
        },  true, true);
    }
    
    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event)
    {
        return super.onKeyUp(keyCode, event);
    }
    
    @Override
    protected ADV_TYPE getAdvType()
    {
        // 显示广告，如果打开且这页需要显示的话
        return ADV_TYPE.NONE;
    }
      
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        
        if(requestCode == SelLocActivity.CODE_REQUEST)
        {
            if(resultCode == Activity.RESULT_OK)
            {              
                mAddr = (Addr)data.getSerializableExtra(Constant.TAG_ADDR);
                address.setText(mAddr.address);
                if(mAddr.district != null)
                {
                    mTitleBar.setLeftText(mAddr.district);
                }
                MyApplication.getContext().setLocMapMode(mAddr);
            }else
            {
                
            }
        }else
        if(requestCode == SelCityActivity.CODE_REQUEST)
        {
            if(resultCode == Activity.RESULT_OK)
            {            
                mArea = (Area)data.getSerializableExtra(Constant.TAG_CITY);
                mTitleBar.setLeftText(mArea.areaName);
                MyApplication.getContext().setLocCityMode(mArea.areaId);
            }
        }else
        if(requestCode == SelCategoryActivity.CODE_REQUEST)
        {
            if(resultCode == Activity.RESULT_OK)
            {
                mCateList = data.getIntegerArrayListExtra(Constant.TAG_CATEGORYS);
            }else
            {
                
            }
        }
    }
       
    @Override
    public void onClick(View v)
    {
        switch(v.getId())
        {
        	//add by huangyue 点击定位地址栏显示定位
	        case R.id.curloc_info:
	        {
	        	showSelLocPopWin();
	        	break;
	        }
	        //end
            case R.id.shake_img:
            {
                startShake();
                break;
            }
            case R.id.loc_cur:
            {
//                MyApplication.getContext().setLocCurMode();
//                setLocationSelected(selLocPopWin.getContentView(), R.id.loc_cur);
//                reLocation(true);
                dissPop();
//                break;
            }
            case R.id.address_refresh:
            {
            	MyApplication.getContext().setLocCurMode();
            	if(selLocPopWin == null){
            		DataCache.setValue(Constant.LOCATION_TYPE, R.id.loc_cur);
            	} else {
            		setLocationSelected(selLocPopWin.getContentView(), R.id.loc_cur_img);
            	}
                reLocation(true);
                break;
            }
            case R.id.loc_map:
            {
                if(selLocPopWin != null)
                    setLocationSelected(selLocPopWin.getContentView(), R.id.loc_map_img);
                SelLocActivity.startActivityResult(this);
                break;
            }
            case R.id.sel_city:
            {
                if(selLocPopWin != null)
                    setLocationSelected(selLocPopWin.getContentView(), R.id.sel_city_img);
                SelCityActivity.startActivityResult(this);
                break;
            }
            case R.id.pop_cancel:
            {
                dissPop();
                break;
            }
            case R.id.add_cate_img:
            case R.id.add_cate_bnt:
            {
                SelCategoryActivity.startActivityResult(this, true, mCateList);
                break;
            }
        }
    }

    @Override
    public void onShake()
    {
        startShake();
    }
    
    @Override
    public void onError()
    {
        address.setText(R.string.get_location_err);
        loc_loading.setVisibility(View.GONE);
        address_refresh.setVisibility(View.VISIBLE);
    }

    @Override
    public void onLocation(Location loc)
    {       
        mCurLocation = loc;        
        address.setText(R.string.finding_city);
    }

    @Override
    public void onGetAddr(MKAddrInfo addr)
    {
        loc_loading.setVisibility(View.GONE);
        address_refresh.setVisibility(View.VISIBLE);
        if(addr != null)
        {
            address.setText(addr.strAddr);
            if(MyApplication.getContext().getLocMode() == Constant.LOC_CUR)
            {
                mTitleBar.setLeftText(addr.addressComponents.district);
            }
        }else
        {
            address.setText(R.string.loc_not_found);
        }
    }
    
    private void initViews()
    {
        viewFlow = (ViewFlow) findViewById(R.id.viewflow);
        mAdvAdapter = new AdvListAdapter(this);
        viewFlow.setAdapter(mAdvAdapter);
        CircleFlowIndicator indic = (CircleFlowIndicator) findViewById(R.id.viewflowindic);
        viewFlow.setFlowIndicator(indic);
        shake_img = (ImageView)findViewById(R.id.shake_img);
        shake_num = (TextView)findViewById(R.id.shake_num);
        add_cate_img = (ImageView)findViewById(R.id.add_cate_img);
        add_cate_bnt = (Button)findViewById(R.id.add_cate_bnt);
        address = (TextView)findViewById(R.id.address);
        address_refresh = (ImageView)findViewById(R.id.address_refresh);
        loc_loading = (ProgressBar)findViewById(R.id.loc_loading);
        
        cate_0 = (TextView)findViewById(R.id.cate_0);
        cate_1 = (TextView)findViewById(R.id.cate_1);
        cate_2 = (TextView)findViewById(R.id.cate_2);
        
        shake_img.setOnClickListener(this);
        add_cate_img.setOnClickListener(this);
        add_cate_bnt.setOnClickListener(this);
        address_refresh.setOnClickListener(this);
        findViewById(R.id.curloc_info).setOnClickListener(this);
        
//        checkShakeTip();
        showToast(getString(R.string.shake_tip));
    }
    
//    private void checkShakeTip()
//    {
//        if(MyApplication.getContext().isFirst)
//        {
//            MyApplication.getContext().isFirst = false;
//            final View v = findViewById(R.id.shake_tip);
//            v.setVisibility(View.VISIBLE);
//            Animation anim = AnimationUtils.loadAnimation(this, R.anim.anim_fade_out);
//            anim.setAnimationListener(new AnimationListener()
//            {
//                @Override
//                public void onAnimationStart(Animation animation){  }
//                @Override
//                public void onAnimationRepeat(Animation animation){}
//                @Override
//                public void onAnimationEnd(Animation animation)
//                {
//                    v.setVisibility(View.GONE);
//                }
//            });
//            v.startAnimation(anim);
//        }
//    }
    
    private void showCateViews()
    {
        if(mCateList == null || mCateList.size() == 0 || mCateList.get(0) < 0)
        {
            cate_0.setText(R.string.all_cate);
            cate_0.setVisibility(View.VISIBLE);
            cate_1.setVisibility(View.GONE);
            cate_2.setVisibility(View.GONE);
        }else
        {
            int size = mCateList.size();
            for(int i =0; i <size; i++)
            {
                if(i == 0)
                {
                    cate_0.setText(DataCacheManager.getInstance().getCateNameById(mCateList.get(i)));
                    cate_0.setVisibility(View.VISIBLE);
                    cate_1.setVisibility(View.GONE);
                    cate_2.setVisibility(View.GONE);
                }else
                if(i == 1)
                {
                    cate_1.setText(DataCacheManager.getInstance().getCateNameById(mCateList.get(i)));
                    cate_1.setVisibility(View.VISIBLE);
                    cate_2.setVisibility(View.GONE);
                }else
                if(i == 2)
                {
                    cate_2.setText(DataCacheManager.getInstance().getCateNameById(mCateList.get(i)));
                    cate_2.setVisibility(View.VISIBLE);
                }else
                if(i == 3)
                {
                    cate_2.setText(cate_2.getText() + "...");
                }
            }
        }
    }
    
    private void showShakeNumView()
    {
        CountAction action = new CountAction();
        action.setActionListener(new CountAction.ActionListener<ShakeCount>()
        {
            @Override
            public void onSucceed(ShakeCount result)
            {     
                if(result != null)
                {
                    DecimalFormat df = new DecimalFormat("###,###");
                    shake_num.setText(Html.fromHtml(String.format(TX_SHAKE_NUM, df.format(result.count))));
                }else
                {
                    shake_num.setText("");
                }
            }

            @Override
            public void onError(int resultCode)
            {
                shake_num.setText("");
            }
        });
        ProtocolManager.getProtocolManager().submitAction(action);
    }
        
    private void showSelLocPopWin()
    {
        if(selLocPopWin == null)
        {
            View contentView = LayoutInflater.from(this).inflate(R.layout.popview_sleloc, null);
            selLocPopWin = new PopupWindow(contentView,ViewGroup.LayoutParams.FILL_PARENT,ViewGroup.LayoutParams.FILL_PARENT, true);
            selLocPopWin.setTouchable(true);
            selLocPopWin.setOutsideTouchable(true);
            
            int id = DataCache.getInt(Constant.LOCATION_TYPE, R.id.loc_cur_img);
            setLocationSelected(contentView, id);
            
            contentView.findViewById(R.id.loc_cur).setOnClickListener(this);
            contentView.findViewById(R.id.loc_map).setOnClickListener(this);
            contentView.findViewById(R.id.sel_city).setOnClickListener(this);
            contentView.findViewById(R.id.pop_cancel).setOnClickListener(this);
            
            contentView.setOnKeyListener(new OnKeyListener()
            {
                @Override
                public boolean onKey(View v, int keyCode, KeyEvent event)
                {
                    if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK)
                    {
                        dissPop();
                        isPopBack = true;
                    }
                    return false;
                }
            });
        }
        selLocPopWin.showAtLocation(getWindow().getDecorView(),Gravity.BOTTOM, 0, 0);
    }
    
    private void dissPop()
    {
        if(selLocPopWin != null && selLocPopWin.isShowing())
        {
            selLocPopWin.dismiss();
        }
    }
       
    private void startShake()
    {
        if(mShakeAnim == null)
        {
            mShakeAnim = AnimationUtils.loadAnimation(this, R.anim.anim_shake_0);
        }
        Animation anim = shake_img.getAnimation();
        if(anim == null || !anim.hasStarted())
        {
            shake_img.startAnimation(mShakeAnim);
            doVibreat();
            if(MyApplication.getContext().isSoundOn()){
            	doSound();
            }
            shake_img.postDelayed(new Runnable()
            {
                @Override
                public void run()
                {
                    shake_img.clearAnimation();          
                    goShakeResult();
                }
            }, 2000);
        }        
        /**
        final AnimationDrawable anim = (AnimationDrawable)shake_img.getBackground();
        if(anim != null && !anim.isRunning())
        {
        	doVibreat();
            anim.start();            
            shake_img.postDelayed(new Runnable()
            {
                @Override
                public void run()
                {
                    anim.stop();                    
                    goShakeResult();
                }
            }, 1600);
        }*/
    }
    
    private void doVibreat()
    {
        Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE); 
        // OFF/ON/OFF/ON...  
        long[] pattern = {100, 1200, 0, 0}; 
        //-1不重复，非-1为从pattern的指定下标开始重复
        vibrator.vibrate(pattern, -1);
    }
    
    /**
     * 播放系统资源的铃音
     */
    private void doSound()
    {       
        if(MyApplication.getContext().isSoundOn())
        {                 
            MediaPlayer mediaPlayer0 = MediaPlayer.create(
                    ShakeShopActivity.this, R.raw.sound_shake);
            if (mediaPlayer0 == null)
            {
                Log.e("doSound", "--->palySystemRing error");
                return;
            }
            mediaPlayer0.start();
            Log.d("doSound", "--->palySystemRing");
        }
    }
    
    private void goShakeResult()
    {
        double lat = 0;
        double lon = 0;
        int areaId = 0;
        int mLocMode = MyApplication.getContext().getLocMode();
        
        if(mLocMode == Constant.LOC_MAP)
        {
            if(mAddr == null)
            {
                mAddr =  MyApplication.getContext().getLocMapValue();
            }
            lat = mAddr.latitude;
            lon = mAddr.longitude;
        }else
        if(mLocMode == Constant.LOC_CUR)
        {
            lat = mCurLocation.getLatitude();
            lon = mCurLocation.getLongitude();
        }else
        {
            // TODO 镇区location
            lat = mCurLocation.getLatitude();
            lon = mCurLocation.getLongitude();
            if(mArea != null)
            {
                areaId = mArea.areaId;
            }else
            {
                areaId = MyApplication.getContext().getLocCityValue();
            } 
        }
                            
        ShakeResultActivity.startActivity(ShakeShopActivity.this, 
            new FindCondition(lon, lat, areaId, mCateList));
    }
    
    private void checkLocation()
    {        
        if(mMapManager.getMyLoation() == null)
        {
            reLocation(false);
        }else
        {
            mCurLocation = mMapManager.getMyLoation();
            if(mMapManager.getMyAddrInfo() != null)
            {
                
                int mod = MyApplication.getContext().getLocMode();
                if(mod == Constant.LOC_CUR)
                {
                    mTitleBar.setLeftText(mMapManager.getMyAddrInfo().addressComponents.district);
                } else if(mod == Constant.LOC_CITY){
                	mMapManager.getMyAddrInfo().strAddr = "广东省东莞市" + Util.getCityText(this);
                }
                address.setText(mMapManager.getMyAddrInfo().strAddr);
                loc_loading.setVisibility(View.GONE);
                address_refresh.setVisibility(View.VISIBLE);
            }else
            {
                loc_loading.setVisibility(View.VISIBLE);
                address_refresh.setVisibility(View.GONE); 
                address.setText(R.string.finding_city);
                mMapManager.startGetAddr();
                if(MyApplication.getContext().getLocMode() == Constant.LOC_MAP)
                {
                    if(!TextUtils.isEmpty(MyApplication.getContext().getLocMapValue().address))
                    {
                        address.setText(MyApplication.getContext().getLocMapValue().address);
                    }
                }
            }
        }
    }
    
    private void reLocation(boolean myself)
    {       
        mMapManager.setOnLocationListener(this);
        if(myself)
        {
            mMapManager.startLocation(true,false);
        }else
        {
            mMapManager.startLocation(true);
        }
        address.setText(R.string.locating);
        loc_loading.setVisibility(View.VISIBLE);
        address_refresh.setVisibility(View.GONE);
    }
    
    private void startAutoSlidAdv()
    {
        if(mSlidAdvThread == null)
        {
            mSlidAdvThread = new CycledThread(new Runnable()
            {
                @Override
                public void run()
                {
                    runOnUiThread(new Runnable()
                    {
                        public void run()
                        {
                            int size = viewFlow.getViewsCount();
                            if(size > 0)
                            {
                                viewFlow.snapToNextScreen();
                            }
                        }
                    });
                }
            },6000);            
            mSlidAdvThread.start();
        }
    }
    
    private void setLocationSelected(View parent, int id)
    {
    	DataCache.setValue(Constant.LOCATION_TYPE, id);
    	parent.findViewById(R.id.loc_cur_img).setVisibility(View.GONE);
    	parent.findViewById(R.id.loc_map_img).setVisibility(View.GONE);
    	parent.findViewById(R.id.sel_city_img).setVisibility(View.GONE);
    	
    	View v = parent.findViewById(id);
    	if(v != null)
    	{
    	    v.setVisibility(View.VISIBLE);
    	}
    }
    
    private void stopAutoSlidAdv()
    {
        if(mSlidAdvThread != null && mSlidAdvThread.isAlive())
        {
            mSlidAdvThread._stop();
            mSlidAdvThread = null;
        }
    }
    
    public static void startActivity(Context context)
    {
        context.startActivity(getStartActivity(context));
    }
    
    public static Intent getStartActivity(Context context)
    {
        Intent it = new Intent(context, ShakeShopActivity.class);
        return it;
    }
}
